package com.foxit.setting;

import java.io.*;
import java.net.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.UnknownHostException;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class SetControl extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
       request.setCharacterEncoding("UTF-8");
       PrintWriter out = response.getWriter();
       try {
          MongoClient mongo = new MongoClient("192.201.108.97", 27017);
          DB db = mongo.getDB("settingdb");
          DBCollection table = db.getCollection("control");
          out.println("<HTML><head><style>table,th,td { border:1px solid black;border-collapse:collapse; } </style></head><body>");
// del user
          String d = request.getParameter("del"); 
          if(d != null && d.length()!=0) {
             table.remove(new BasicDBObject().append("user", d));
             response.sendRedirect("./SetControl");
             return;
          }
// javascript
          outscript(out);
          int i=0;
// modify user
          String m = request.getParameter("modify");
          if(m != null && m.length()!=0) {
             BasicDBObject query = new BasicDBObject("user", m);
             DBCursor cursor = table.find(query);
             if(cursor.hasNext()) {
                Control s = (Control) JSON.parseObject(cursor.next().toString(),Control.class);
                String advertiser= s.getAdvertiser();
                String adlist = s.getAdlist();
                DBCollection t_adrule = db.getCollection("adrule");
                List vlist=(List) t_adrule.distinct("advertiser"); 
                List rlist=(List) t_adrule.distinct("adrule"); 
                String[] adv = null;
                String[] rule = null;
                if(!advertiser.equals("ALL")) {
                   if(advertiser != null && advertiser.length()!=0) {
                      adv = advertiser.split(",");
                   }
                   if(adlist != null && adlist.length()!=0) {
                      rule = adlist.split(",");  
                   }
                }
                if(adv != null && adv.length !=0) {
                   for(i=0;i < adv.length;i++) {
                      vlist.remove(adv[i]);
                   }
                }
                if(rule != null && rule.length != 0) {
                   for(i=0;i < rule.length;i++) {
                      rlist.remove(rule[i]);
                   }
                }
                if(!advertiser.equals("ALL")) {
                   selectpriv(out,m,0,0,vlist,adv,rlist,rule);
                } else {
                   selectpriv(out,m,1,0,vlist,adv,rlist,rule);
                }
                return;
             } else {
                out.println("can't find the user("+m+")<br><br>");
                out.println("<a href='.SetControl'>回SetControl頁面</a>");
                return; 
             }
          }
// add  or updatea user
          String u = request.getParameter("user");
          if(u != null && u.length()!=0) {
             String admin = request.getParameter("admin");
             String n=request.getParameter("n");
             if(admin != null && admin.length()!= 0) {
                if(admin.equals("1")) {
                   if(n != null && n.equals("0")) {
                      table.remove(new BasicDBObject().append("user",u));
                   }
                   BasicDBObject doc = new BasicDBObject("user",u)
                      .append("advertiser","ALL")
                      .append("adlist","ALL");
                   table.insert(doc);
                }
             } else {
                String[] adv = request.getParameterValues("AdvertiserCodes");
                String[] rule = request.getParameterValues("AdruleCodes");
                if((adv != null && adv.length != 0) || (rule!=null && rule.length != 0)) {
                   // insert
                   String v=""; 
                   String r=""; 
                   if(adv != null) {
                      for(i=0;i < adv.length;i++) {
                         if(i != 0) v += ",";
                         v += adv[i];
                      }
                   }
                   if(rule != null) {
                      for(i=0;i < rule.length;i++) {
                         if(i != 0) r += ",";
                         r += rule[i];
                      }
                   }
                   if(n != null && n.equals("0")) {
                      table.remove(new BasicDBObject().append("user",u));
                   }
                   BasicDBObject doc = new BasicDBObject("user",u)
                         .append("advertiser",v)
                         .append("adlist",r);
                   table.insert(doc);
                } else {
                   DBCollection t_adrule = db.getCollection("adrule");
                   List vlist=(List) t_adrule.distinct("advertiser"); 
                   List rlist=(List) t_adrule.distinct("adrule"); 
                   selectpriv(out,u,0,1,vlist,null,rlist,null);
                   return;
                }
             } 
          }
// default page
          out.println("<FORM action='./SetControl'><table border='1' style='width:300px'><tr><th colspan=5>FOXIT 成效分析管控系統</th></tr>");
          out.println("<tr><td colspan=5><a href='./Sethome'>回setting tool首頁</a></td></tr>"); 
          DBCursor cursor = table.find();
          while (cursor.hasNext()) {
             Control s = (Control) JSON.parseObject(cursor.next().toString(),Control.class);
             if(s.getAdvertiser().equals("ALL")) {
                out.println("<tr><td>"+s.getUser()+"</td><td><button name='modify' value='"+s.getUser()+"'>modify</button></td><td>系統管理員</td><td></td><td>   <a href='./SetControl?del="+s.getUser()+"'>delete</a></button></td></tr>");
             } else {
                out.println("<tr><td>"+s.getUser()+"</td><td><button name='modify' value='"+s.getUser()+"'>modify</button></td><td></td><td></td><td>   <a href='./SetControl?del="+s.getUser()+"'>delete</a></button></td></tr>");
             }
          }
          cursor.close();
          out.println("<tr><td>增加新使用者</td><td><input type=text name='user'></td><td><input type='submit' value='新增'></td><td></td><td></td></tr>");
          out.println("<tr><td colspan=5><a href='./DumpUser?couch=localhost'>dump all user to online</a></td></tr>");
          out.println("</table></FORM><br>");
          out.println("</body></html>");
       } catch (Exception ex) {
          out.println(ex.getMessage());
       }

    }

    public void selectpriv(PrintWriter out,String user,int admin,int n,List vlist,String[] adv,List rlist,String[] rule) {
       int i=0;
       out.println("<form name='Example' method=GET action='./SetControl' onsubmit='DoSumbit();'>");
       out.println("<input type='hidden' name='user' value='"+user+"'>");
       if(n == 0) {
          out.println("<input type='hidden' name='n' value='0'>");
       } else {
          out.println("<input type='hidden' name='n' value='1'>");
       }
       out.println("<table border=0 cellpadding=3 cellspacing=1>");
       out.println("<tr><td colspan=3><a href='./SetControl'>回管控首頁</a></td></tr>");
       if(admin==1) {
          out.println("<tr><td colspan=3><input type='checkbox' name='admin' value='1' checked>系統管理員</td></tr>");
       } else {
          out.println("<tr><td colspan=3><input type='checkbox' name='admin' value='1'>系統管理員</td></tr>");
       }
       out.println("<tr><th>list</th><th></th><th>加入權限</th></tr>");
       out.println("<tr><td><select name='Advertiser' size='9' multiple='multiple'>");
       if(vlist != null) {
          for(i=0;i < vlist.size();i++) {
             out.println("<option value='"+vlist.get(i).toString()+"'>"+vlist.get(i).toString()+"</option>");
          }
       }
       out.println("</select></td>");
       out.println("<td align='center' valign='middle'><input type='Button' value='Add >>' style='width:100px' onClick='SelectMoveRows(document.Example.Advertiser,document.Example.AdvertiserCodes)'><br><br>");
       out.println("<input type='Button' value='<< Remove' style='width:100px' onClick='SelectMoveRows(document.Example.AdvertiserCodes,document.Example.Advertiser)'></td>");
       out.println("<td><select name='AdvertiserCodes' size='9' multiple='multiple'>");
       if(adv != null) {
          for(i=0;i < adv.length;i++) {
             out.println("<option value='"+adv[i]+"'>"+adv[i]+"</option>");
          }
       }
       out.println("</select></td>");
       out.println("<tr><td><select name='Adrule' size='9' multiple='multiple'>");
       if(rlist != null) {
          for(i=0;i < rlist.size();i++) {
             out.println("<option value='"+rlist.get(i).toString()+"'>"+rlist.get(i).toString()+"</option>");
          }
       }
       out.println("</select></td>");
       out.println("<td align='center' valign='middle'><input type='Button' value='Add >>' style='width:100px' onClick='SelectMoveRows(document.Example.Adrule,document.Example.AdruleCodes)'><br><br><input type='Button' value='<< Remove' style='width:100px' onClick='SelectMoveRows(document.Example.AdruleCodes,document.Example.Adrule)'></td>");
       out.println("<td><select name='AdruleCodes' size='9' multiple='multiple'>");
       if(rule != null) {
          for(i=0;i < rule.length;i++) {
             out.println("<option value='"+rule[i]+"'>"+rule[i]+"</option>");
          }
       }
       out.println("</select></td></tr>");
       out.println("<tr><td colspan=3><input type='submit'></td></tr>");
       out.println("</table></form></body></html>");
       return;
    }

    public void outscript(PrintWriter out) {
       out.println("<script language='Javascript'>");
       out.println("function DoSumbit() { for (i=document.Example.AdvertiserCodes.options.length - 1; i>=0; i--) { document.Example.AdvertiserCodes.options[i].selected = true;} for (i=document.Example.AdruleCodes.options.length - 1; i>=0; i--) { document.Example.AdruleCodes.options[i].selected = true; } }");
       out.println("function SelectMoveRows(SS1,SS2) { var SelID=''; var SelText=''; for (i=SS1.options.length - 1; i>=0; i--) { if (SS1.options[i].selected == true) { SelID=SS1.options[i].value; SelText=SS1.options[i].text; var newRow = new Option(SelText,SelID); SS2.options[SS2.length]=newRow; SS1.options[i]=null; } } SelectSort(SS2); }");
       out.println("function SelectSort(SelList) { var ID=''; var Text=''; for (x=0; x < SelList.length - 1; x++) { for (y=x + 1; y < SelList.length; y++) { if (SelList[x].text > SelList[y].text) { ID=SelList[x].value; Text=SelList[x].text; SelList[x].value=SelList[y].value; SelList[x].text=SelList[y].text; SelList[y].value=ID; SelList[y].text=Text; } } } }");
       out.println("</script>");
    }
} 
